package spindles.api.services;

import static spindles.api.util.ErrorMessages.MAX_PLOTS_EXCEEDED;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.io.FilenameUtils;

import spindles.api.db.DAO;
import spindles.api.domain.CutoffFrequency;
import spindles.api.domain.Epoch;
import spindles.api.domain.Person;
import spindles.api.util.FileUtil;
import spindles.api.util.UserException;

public abstract class PlotExport {
	
	private DAO<Epoch> epochDAO = new DAO<Epoch>(Epoch.class, "sessionPartID");
	
	public static final int MAX_PLOTS = 3;
	
	private List<Epoch> epochs = 
		new ArrayList<Epoch>();
	
	private List<CutoffFrequency> cutOffs =
		new ArrayList<CutoffFrequency>();
	
	protected String path;
	
	private boolean softCriterion;
	
	public PlotExport(boolean softCriterion){
		this.softCriterion = softCriterion;
	}
	
	public boolean withSoftCriterion(){
		return softCriterion;
	}
	
	public void init(String path, Person person) throws UserException {						
		this.path = FileUtil.writeToDir(FilenameUtils.getFullPath(path) + 
				person.getLastName() + person.getId() + 
				System.getProperty("file.separator"));
	}
	
	public Iterator<Epoch> getData(long part) {
		return epochDAO.findAllSorted(part).iterator();
	}
	
	abstract int export(int npart, int nepoch) throws UserException;

	abstract Format getFormat();
	
	public void addEpoch(Epoch e, CutoffFrequency freq) throws UserException{
		if(epochs.size() >= MAX_PLOTS){
			throw new UserException(MAX_PLOTS_EXCEEDED);
		}
		
		epochs.add(e);		
		cutOffs.add(freq);		
	}
	
	public Epoch getEpoch(int i){
		return epochs.get(i);
	}
	
	public int size(){
		return epochs.size();
	}
	
	public void clear(){
		epochs.clear();
		cutOffs.clear();
	}
	
	public String getLabel(int i){
		return cutOffs.get(i).getLabel();
	}
	
	public double[] getData(int i){		
		CutoffFrequency freq = cutOffs.get(i);		
		return getEpoch(i).getFilteredEEGSamples(freq);		
	}	

}
